﻿using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Zhao.Common;
using Zhao.Common.Helper;
using Zhao.IServer.User;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Repository.Base;
using Zhao.Repository.UnitOfWork;

namespace Zhao.Service.User
{
    public class AdminServer : BaseService<Admin>, IAdminServer
    {
        private readonly IUnitOfWork _unitOfWork;
        public AdminServer(IBaseRepository<Admin> baseDal, IUnitOfWork unitOfWork) : base(baseDal, unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<bool> DelAdmin(int Id)
        {
           Admin admin=await _Client.Queryable<Admin>()
                .Where(x=>x.Id==Id)
                .FirstAsync();
            if (admin != null)
            {
                admin.IsDelete = true;
                return await _Client.Updateable(admin).UpdateColumns(x=>new {x.IsDelete}).ExecuteCommandHasChangeAsync();
            }
            return await Task.FromResult(false);
        }

        public async Task<PageModel<AdminDto>> GetPageAdmin(Expression<Func<Admin, Roles,Venues, bool>> expressionable, int pageIndex, int pageSize)
        {
            //获取总条数
            RefAsync<int> totalCount = 0;
            var list= await _Client.Queryable<Admin>()
                .LeftJoin<Roles>((a,b) =>a.Role==b.RoleID)
                .LeftJoin<Venues>((a,b,c)=>a.VenueId==c.VenueID)
                .WhereIF(expressionable != null, expressionable)
                .Select((a,b,c)=> new AdminDto
                {
                    Id = a.Id,
                    uName=a.UserName,
                    email=a.Email,
                    status=a.Status,
                    rName=b.Description,
                    role=b.RoleID,
                    lastatTime=a.LastLoginAt,
                    lastIp=a.LastLoginIp,
                    fName=a.FName,
                    phone=a.Phone,
                    venueName=c.VenueName
                }).ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);

            int totalPage = (Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt();

            return new PageModel<AdminDto>() { count = totalCount, PageCount = totalPage, PageIndex = pageIndex, PageSize = pageSize, data = list, code = totalCount == 0 ? -1 : 0, msg = totalCount == 0 ? "未查询到任何数据" : "" };
        }


        /// <summary>
        /// 返回登录用户的详情信息
        /// </summary>
        /// <typeparam name="AdminInfo"></typeparam>
        /// <param name="account"></param>
        /// <param name="paw">加密过后的密码</param>
        /// <returns></returns>
        public async Task<AdminInfoDto> Login(string account,string paw, string ip)
        {
            // 合并查询：一次性获取用户信息及关联角色
            var adminInfo = await _Client.Queryable<Admin>()
                .LeftJoin<Roles>((a, r) => a.Role == r.RoleID)
                .Where((a, r) => a.UserName == account && a.Password == paw)
                .Select((a, r) => new AdminInfoDto
                {
                    Id = a.Id,
                    Name = a.FName,
                    Phone = a.Phone,
                    Email = a.Email,
                    RoleName = r.RoleName,
                    VenueId = a.VenueId,
                    Role = a.Role,
                    Imageurl=a.IamgeUrl
                })
                .FirstAsync();

            if (adminInfo == null) return null;

            // 按需更新：添加最后登录时间更新示例
            await _Client.Updateable<Admin>()
                .SetColumns(a => a.LastLoginAt == DateTime.Now)
                .SetColumns(a=> a.LastLoginIp == ip)
                .Where(a => a.Id == adminInfo.Id)
                .ExecuteCommandAsync();

            return adminInfo;
        }


        /// <summary>
        /// 返回个人详情信息（个人中心使用 ||管理员）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AdminDto> ByIdAdminInfo(int id)
        {
            // 合并查询：一次性获取用户信息及关联角色
            var adminInfo = await _Client.Queryable<Admin>()
                .LeftJoin<Roles>((a, b) => a.Role == b.RoleID)
                .Where((a, b) => a.Id == id)
                .Select((a, b) => new AdminDto
                {
                    Id = a.Id,
                    uName = a.UserName,
                    email = a.Email,
                    rName = b.Description,
                    lastatTime = a.LastLoginAt,
                    lastIp = a.LastLoginIp,
                    fName = a.FName,
                    phone = a.Phone,
                    img=a.IamgeUrl
                })
                .FirstAsync();

            if (adminInfo == null) return null;

            // 按需更新：添加最后登录时间更新示例
            await _Client.Updateable<Admin>()
                .SetColumns(a => a.LastLoginAt == DateTime.Now)
                .Where(a => a.Id == adminInfo.Id)
                .ExecuteCommandAsync();

            return adminInfo;
        }


        /// <summary>
        /// 返回个人详情信息（个人中心使用 ||球馆管理员）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AdminDto> ByIdAdminVenuInfo(Guid guid,int id)
        {
            // 合并查询：一次性获取用户信息及关联角色
            var adminInfo = await _Client.Queryable<Admin>()
                .LeftJoin<Roles>((a, b) => a.Role == b.RoleID)
                .LeftJoin<Venues>((a, b, c) => a.VenueId == c.VenueID)
                .Where((a, b, c) => a.Id == id && c.VenueID==guid)
                .Select((a, b, c) => new AdminDto
                {
                    Id = a.Id,
                    uName = a.UserName,
                    email = a.Email,
                    rName = b.Description,
                    lastatTime = a.LastLoginAt,
                    lastIp = a.LastLoginIp,
                    fName = a.FName,
                    phone = a.Phone,
                    venueName = c.VenueName,
                    img = a.IamgeUrl,
                    LicenseImage=c.License
                })
                .FirstAsync();

            if (adminInfo == null) return null;

            // 按需更新：添加最后登录时间更新示例
            await _Client.Updateable<Admin>()
                .SetColumns(a => a.LastLoginAt == DateTime.Now)
                .Where(a => a.Id == adminInfo.Id)
                .ExecuteCommandAsync();

            return adminInfo;
        }

        /// <summary>
        /// 修改管理员个人资料(按需修改)
        /// </summary>
        /// <returns></returns>
        public async Task<bool> UpdateIndividualInfo(AdminInfoDto dto)
        {
            if (dto == null) return false;

            //开始修改
         return  await _Client.Updateable<Admin>()
                .SetColumnsIF(!dto.Imageurl.IsNullOrWhiteSpace(),x=>x.IamgeUrl==dto.Imageurl)
                .SetColumnsIF(!dto.Phone.IsNullOrWhiteSpace(), x =>x.Phone==dto.Phone)
                .SetColumnsIF(!dto.Name.IsNullOrWhiteSpace(), x =>x.UserName==dto.Name)
                .SetColumnsIF(!dto.Email.IsNullOrWhiteSpace(), x =>x.Email==dto.Email)
                .Where(x=>x.Id== dto.Id)
                .ExecuteCommandAsync()>0;
        }
    }
}
